package com.cqrt.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.config.CustomObjectMapper;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.dto.RTTemplateLinkDocDTO;
import com.cqrt.entity.RTPreConstraintDO;
import com.cqrt.mapper.RTOutRuleMapper;
import com.cqrt.mapper.RTProjectKnowledgeLinkMapper;
import com.cqrt.mapper.RTProjectMapper;
import com.cqrt.mapper.RTTaskMapper;
import com.cqrt.service.RTProjectKnowledgeLinkService;
import com.cqrt.service.RTTaskService;
import com.cqrt.service.RtWorkItemService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchTypeDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.rpm.entityconvert.BaseConvert;
import com.hustcad.plm.rpm.model.dto.issue.CreatIssueLinkDTO;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.outrule.TyppmOutRuleDTO;
import com.hustcad.plm.rpm.model.dto.remote.BatchInsertDocVO;
import com.hustcad.plm.rpm.model.dto.remote.DocDetailsVO;
import com.hustcad.plm.rpm.model.entity.outrule.TyppmOutRuleItem;
import com.hustcad.plm.rpm.model.vo.outrule.OutRuleQC;
import com.hustcad.plm.rpm.service.outrule.TyppmOutRuleService;
import com.hustcad.plm.rpm.service.remote.TyppmRemotePdmService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.ppm.api.service.outrule.OutRuleItemService;
import com.ty.ppm.model.dto.outrule.OutRuleItemDTO;
import com.ty.ppm.model.entity.outrule.OutRuleItem;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class JobAop {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private BaseConvert baseConvert;
    @Resource
    private OutRuleItemService outRuleItemService;
    @Resource
    private TyppmOutRuleService typpmOutRuleService;
    @Resource
    private TyppmRemotePdmService typpmRemotePdmService;
    @Resource
    private RTProjectMapper rtProjectMapper;
    @Value("${query.url}")
    private String queryConditionUrl;
    @Resource
    private RTProjectKnowledgeLinkService rtProjectKnowledgeLinkService;
    @Resource
    private RTTaskMapper rtTaskMapper;
    @Resource
    private RTOutRuleMapper rtOutRuleMapper;
    @Resource
    private RTTaskMapper taskMapper;
    @Resource
    private RTTaskService rtTaskService;
    @Resource
    private RtWorkItemService workItemService;

    @Resource
    private RTProjectKnowledgeLinkMapper rtProjectKnowledgeLinkMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @SneakyThrows
    @Around("execution(* com.hustcad.plm.rpm.service.job.TyppmJobService.insertJob(..))")
    public Object aroundControllerMethods(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        TyppmJobDTO typpmJobDTO = (TyppmJobDTO)args[0];
        if (StrUtil.isNotBlank(typpmJobDTO.getParentOID())){
            typpmJobDTO.setState("未读");
            typpmJobDTO.setStateDisplayName("未读");
            Map<String, List<String>> ibaAttribute = typpmJobDTO.getIbaAttribute();
            if (ibaAttribute==null){
                ibaAttribute = new HashMap<>();
            }
            ibaAttribute.put("ExecutionStatus",Arrays.asList("正常"));
            ibaAttribute.put("ParentTask", Arrays.asList("true"));
            typpmJobDTO.setIbaAttribute(ibaAttribute);
            return point.proceed(args);
            //继承父任务交付物规则
//            Map<String, Object> params = new HashMap<>();
//            params.put("containeroid",typpmJobDTO.getParentOID());
//            params.put("usertype", "USER");
//            params.put("jobOid", typpmJobDTO.getParentOID());
//            params.put("markfordelete", 0L);

//            PageInfo<OutRule> outRulePageInfo = outRuleService.queryOutRuleByPage(params);
//            List<TyppmOutRuleDTO> list = typpmOutRuleService.queryOutRuleByPage(
//                    typpmJobDTO.getParentOID(), null, null, null).getList();
//            List<TyppmOutRuleDTO> l=new ArrayList<>();
//            for (TyppmOutRuleDTO typpmOutRuleDTO : list) {
//                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(typpmOutRuleDTO));
//                String status = jsonObject.getString("status");
//                if (StrUtil.isBlank(status)){
//                    continue;
//                }
//                if (status.equals("已完成")){
//                    continue;
//                }
//                String ruleDisplayName = jsonObject.getString("ruleDisplayName");
//                if (StrUtil.isBlank(ruleDisplayName)){
//                    continue;
//                }
//                if (!ruleDisplayName.contains("立即提交:否")){
//                    continue;
//                }
//                l.add(typpmOutRuleDTO);
//            }
//            if (CollUtil.isNotEmpty(l)) {
//                List<OutRuleVO> outRules = baseConvert.copyToList(l, OutRuleVO.class);
//                List<TyppmOutRuleItem> outRuleItems = this.getOutRuleItemList(
//                        outRules.stream().map(OutRuleVO::getOid).collect(Collectors.toList()));
//                for (OutRuleVO outRule : outRules) {
//                    OutRuleParamVO outRuleVO = new OutRuleParamVO();
//                    List<TyppmOutRuleItem> outRuleItemList = new ArrayList<>();
//                    for (TyppmOutRuleItem outRuleItem : outRuleItems) {
//                        if (!outRuleItem.getOutputRuleOid().equals(outRule.getOid()))
//                            continue;
//                        outRuleItem.setOid(snowflakeIdComponent.getInstance().nextId().toString());
//                        outRuleItemList.add(outRuleItem);
//                    }
//                    outRule.setJobOid(typpmJobDTO.getOid());
//                    outRule.setOid(snowflakeIdComponent.getInstance().nextId().toString());
//                    outRuleVO.setOutRule(outRule);
//                    outRuleVO.setOutRuleItemList(baseConvert.copyToList(outRuleItemList, OutRuleItemVO.class));
////                    this.typpmOutRuleService.insertOutRule(outRuleVO);
//                }
//            }
        }
        return point.proceed();
    }


    private List<TyppmOutRuleItem> getOutRuleItemList(List<String> oldRuleOidList) {
        List<BigInteger> is = oldRuleOidList.stream().map(BigInteger::new).collect(Collectors.toList());

        List<OutRuleItem> outRuleItems = new ArrayList<>();
        if (is.size()>999){
            int i = is.size() / 999;
            for(int j=0; j<= i; j++){
                OutRuleItemDTO params = new OutRuleItemDTO();
                params.setMarkForDelete(0L);
                if (i==j){
                    params.setOldRuleOidList(is.subList(j*999, is.size()));
                }else {
                    params.setOldRuleOidList(is.subList(j*999,j * 999 +999));
                }
                outRuleItems.addAll(this.outRuleItemService.listOutRuleItemByRuleOidList(params));
            }
        }else {
            OutRuleItemDTO params = new OutRuleItemDTO();
            params.setOldRuleOidList(is);
            params.setMarkForDelete(0L);
            outRuleItems=this.outRuleItemService.listOutRuleItemByRuleOidList(params);
        }
        return this.baseConvert.copyToList(outRuleItems, TyppmOutRuleItem.class);
    }

    //验证关联任务是否完成.
    @Around("execution(* com.hustcad.plm.rpm.service.impl.job.TyppmJobServiceImpl.setSubmitState(..))")
    public Object checkRelationshipTaskIsComplete(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        JobStatusUpdateDTO jobStatusUpdateDTO = (JobStatusUpdateDTO) args[0];
        //获取任务ID
        String jobId = jobStatusUpdateDTO.getJobId();
        //查看有没有从任务关联
        BigInteger ajOid = new BigInteger(jobId);
        List<RTPreConstraintDO> rtPreConstraintDOS = rtProjectMapper.selectRelationsByMasterOid(ajOid);
        for (RTPreConstraintDO rtPreconstraintDO : rtPreConstraintDOS){
            BigInteger bjOid = rtPreconstraintDO.getBjoid();
            String state = rtTaskMapper.selectStateByJobOId(bjOid);
            if (!"已完成".equals(state)){
                throw RTErrorCodeEnum.RELATIONSHIP_TASK_IS_NOT_COMPLETE_ERROR.getException("关联从任务未完成");
            }

        }
        // 同步交付物至父任务。
        synDeliverToParentJob(jobId);
        workItemService.updatePlanStatus(jobId, "通过");
        return point.proceed();
    }

    private void synDeliverToParentJob(String jobId) {
        List<JSONObject> data = this.taskMapper.queryParentJobOid(Collections.singletonList(jobId));
        PageInfo<TyppmOutRuleDTO> result1 = this.typpmOutRuleService.queryOutRuleByPage(jobId, "", 1, 10000);
        List<TyppmOutRuleDTO> childDeliverOutRule = result1.getList();
        if(CollUtil.isEmpty(childDeliverOutRule)){
            return;
        }
        BigInteger prj=rtTaskMapper.selectPrjByID(jobId);
        if(CollUtil.isNotEmpty(data)){
            JSONObject json = data.get(0);
            String parentJobOid = json.getString("PARENTJOBOID");
            PageInfo<TyppmOutRuleDTO> result2 = this.typpmOutRuleService.queryOutRuleByPage(parentJobOid, "", 1, 10000);
            List<TyppmOutRuleDTO> parentOutRuleList = result2.getList();
            Map<String, TyppmOutRuleDTO> parentOutRuleMap = parentOutRuleList.stream()
                    .collect(Collectors.toMap(TyppmOutRuleDTO::getRuletypeOid,
                                              item -> item,
                                              (v1, v2) -> v1));
            for (TyppmOutRuleDTO childDeliver : childDeliverOutRule) {
                String childRuleTypeOid = childDeliver.getRuletypeOid();
                if(parentOutRuleMap.containsKey(childRuleTypeOid)){
                    TyppmOutRuleDTO parentOutRule = parentOutRuleMap.get(childRuleTypeOid);
                    BatchInsertDocVO batchInsetDocVO = new BatchInsertDocVO();
                    List<DocDetailsVO> docList = getDocList(childDeliver);
                    batchInsetDocVO.setDocList(docList);
                    batchInsetDocVO.setDocOtype(childDeliver.getParentOtype());
                    batchInsetDocVO.setLocalRepositoryUid("javaPDM");
                    batchInsetDocVO.setParentNodeOid(parentOutRule.getJobOid());
                    batchInsetDocVO.setOutputRuleOid(parentOutRule.getOid());
                    batchInsetDocVO.setParentNodeOtype(TableTypeConstrant.TY_JOB_OTYPE);
                    batchInsetDocVO.setProjectOid(String.valueOf(prj));
                    batchInsetDocVO.setType("OUT");
                    this.typpmRemotePdmService.insertRemoteDoc(batchInsetDocVO);
                }
            }
        }
    }

    private List<DocDetailsVO> getDocList(TyppmOutRuleDTO childDeliver) {
        SearchTypeDTO searchTypeDTO=rtTaskMapper.selectTypeByName(childDeliver.getRuletypeDisplayName());
        SearchConditionDTO conditionDTO=new SearchConditionDTO();
        conditionDTO.setConditionJoint("and");
        String code = childDeliver.getDeliverName().get(0).getCode();
        conditionDTO.setKeyword(code);
        conditionDTO.setNeedCount(false);
        conditionDTO.setPageNum(1);
        conditionDTO.setPageSize(20);
        conditionDTO.setTypeList(Collections.singletonList(searchTypeDTO));

        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
        HttpEntity<SearchConditionDTO> requestEntity = new HttpEntity<>(conditionDTO, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                queryConditionUrl,
                HttpMethod.POST,
                requestEntity,
                String.class
        );
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String jsonBody = responseEntity.getBody();
            ObjectMapper objectMapper = new CustomObjectMapper(); // 应用日期解析规则
            try {
                ResponseResult<PageInfo<ResultEntityVO>> responseResult = objectMapper.readValue(
                        jsonBody,
                        new TypeReference<ResponseResult<PageInfo<ResultEntityVO>>>() {}
                );
                if (ObjectUtil.isNotNull(responseResult)) {
                    // 返回分页数据
                    List<ResultEntityVO> remoteObjList = responseResult.getData().getList();
                    List<ResultEntityVO> filteredList = remoteObjList.stream()
                            .filter(vo -> Objects.equals(vo.getObjectNumber(), code))
                            .collect(Collectors.toList());
                    log.info("filteredList: {}", filteredList);
                    if (CollUtil.isEmpty(filteredList) || filteredList.size() != 1) {
                        throw RTErrorCodeEnum.TYPEOBJ_NOT_EXIST.getException("该类型对象不存在或编码重复");
                    }
                    return BeanUtil.copyToList(filteredList, DocDetailsVO.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //查询交付规则总条数，以及完成与审批中条数
    @Around("execution(* com.hustcad.plm.rpm.service.impl.job.TyppmJobServiceImpl.queryJobPageByParamsChildMark(..))")
    public Object getOutRuleIsComplete(ProceedingJoinPoint point) throws Throwable {
        Map<String, Object> params = (Map<String, Object>) point.getArgs()[0];
        Integer pageNum = (Integer) point.getArgs()[1];
        Integer pageSize = (Integer) point.getArgs()[2];
        PageInfo<TyppmJobDTO> proceed = (PageInfo<TyppmJobDTO>)point.proceed();
        //遍历任务列表，查看每个任务下的交付规则是否完成
        for (TyppmJobDTO typpmJobDTO : proceed.getList()){
            String planoid = typpmJobDTO.getPlanoid();
            if (StringUtils.isBlank(planoid)){
                BigInteger planOid = rtProjectMapper.selectPlanOIDByProjectOID(typpmJobDTO.getProjectID());
                if (planOid!=null){
                    planoid=planOid.toString();
                }
            }
            String planName = rtProjectMapper.selectPlanNameByPlanOid(planoid);
            if(StringUtils.isBlank(planName) || StringUtils.isEmpty(planName)){
                continue;
            }
            Map<String, String> stringStringMap = rtProjectMapper.selectDevelopmentOrderByProjectName(planName);
            if(CollUtil.isNotEmpty(stringStringMap)) {
                //项目开发令
                if (StrUtil.isNotBlank(stringStringMap.get("PROJECT_CODE"))) {
                    typpmJobDTO.setProjectDevelopmentOrder(stringStringMap.get("PROJECT_CODE"));
                }
            }else {
                String projectID = typpmJobDTO.getProjectID();

                String attrFOid="717552793724518400";
                String devCode = rtProjectMapper.selectSecurity(projectID, new BigInteger(attrFOid));
                if(StringUtils.isNotEmpty(devCode)){
                    typpmJobDTO.setProjectDevelopmentOrder(devCode);
                }
            }
            String jobOid = typpmJobDTO.getOid();
            //获取交付规则Oid集合
            List<BigInteger> outRuleOidList = rtOutRuleMapper.selectOutRuleOidByJobOid(jobOid);

            if(CollUtil.isNotEmpty(outRuleOidList)) {
                int completedCount=0;
                int underApprovalCount=0;
                int outRuleDeliverCount=outRuleOidList.size();
                for (BigInteger BigIntegerOutRuleOid : outRuleOidList) {
                    String outRuleOid = BigIntegerOutRuleOid.toString();
                    //查看交付规则下是否有交付物
                    List<BigInteger> bigIntegers = rtOutRuleMapper.selectDeliverOidByOutRuleOid(outRuleOid);
                    if (CollUtil.isEmpty(bigIntegers)){
                        underApprovalCount++;
                        continue;
                    }
                    for (BigInteger bigIntegerOutRuleOid : bigIntegers){
                        String isCompleted = "";
                            isCompleted = rtOutRuleMapper.selectIsDeliverCompleted(bigIntegerOutRuleOid);
                            if (!Objects.equals(isCompleted, "")&&isCompleted!=null &&isCompleted.contains("已生效")) {
                                continue;
                            }else {
                                underApprovalCount++;
                                break;
                        }

                    }
                }
                completedCount = outRuleDeliverCount-underApprovalCount;
                //设置完成数
                typpmJobDTO.setCompletedCount(completedCount);
                //设置审批中数
                typpmJobDTO.setUnderApprovalCount(underApprovalCount);
                //设置总交付物数
                typpmJobDTO.setOutRuleDeliverCount(outRuleDeliverCount);
                String executionStatus = outRuleDeliverCount+"/"+underApprovalCount+"/"+completedCount;
                String progressDescription=completedCount/outRuleDeliverCount*100+"%";
                typpmJobDTO.setProgressDescription(progressDescription);
                if (completedCount==outRuleDeliverCount){
                    typpmJobDTO.setPassStatus("通过");
                    LocalDateTime actualFinshTime = rtTaskMapper.selectActualFinshTime(jobOid);
                    if (actualFinshTime==null){

                        rtTaskMapper.updateActualFinshTime(jobOid);
                    }
                    typpmJobDTO.setActualFinishTime(actualFinshTime);

                }else {
                    typpmJobDTO.setPassStatus("条件通过");
                }
                String ownerOTYPE = typpmJobDTO.getOwnerOTYPE();
                if (StrUtil.isBlank(ownerOTYPE)){
                    typpmJobDTO.setPassStatus("");
                    String attfOid="717545408691830784";
                    rtProjectMapper.updateSecurity(jobOid, new BigInteger(attfOid), "", "");

                }
                typpmJobDTO.setExecutionStatus(executionStatus);
//                List<BigInteger> count=rtTaskMapper.selectKnowledgeLinkDoc(jobOid);
//                if (CollUtil.isNotEmpty(count)){
//                    typpmJobDTO.setKnowledgeLinkDoc("有");
//                }
                List<RTTemplateLinkDocDTO> rtTemplateLinkDocDTOS = rtProjectKnowledgeLinkService.queryTemplateDetailByOid(
                        new BigInteger(jobOid));
                if (CollUtil.isNotEmpty(rtTemplateLinkDocDTOS)){
                    typpmJobDTO.setKnowledgeLinkDoc("有");
                }



            }
            BigInteger prjOid = rtTaskMapper.selectPrjByID(jobOid);
            if("正常".equals(typpmJobDTO.getExStatus())) {


                LocalDateTime actualStartTime = rtTaskMapper.selectStartTime(jobOid);
                typpmJobDTO.setActualStartTime(actualStartTime);
            }
            String projectStatus = rtProjectMapper.selectStatusByProjectOid(prjOid);
            typpmJobDTO.setExStatus(projectStatus);
            if (typpmJobDTO.getJobNamePath()==null||typpmJobDTO.getJobNamePath().equals("")){
                String pjname = rtProjectMapper.selectProjectNameByProjectOid(prjOid.toString());
                typpmJobDTO.setJobNamePath(pjname);
            }

        }
        for (int i=proceed.getList().size()-1;i>=0;i--){
            TyppmJobDTO typpmJobDTO = (TyppmJobDTO) proceed.getList().get(i);
            if (typpmJobDTO.getExStatus().equals("暂停")){
                proceed.getList().remove(i);
            }
        }

        return proceed;

    }


    //删除交付任务与交付物关联
    @Before("execution(* com.hustcad.plm.rpm.controller.outrule.OutRuleController.deleteOutRuleAndDeliverLink(..))")
    public void deleteJobAndDeliverLink(JoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        OutRuleQC outRuleQC = (OutRuleQC) args[0];
        String jobOid = "";
        jobOid = outRuleQC.getJobOid();
        List<String> deliverOidList = outRuleQC.getDeliverOidList();
        if (!Objects.equals(jobOid, "") && jobOid != null && CollUtil.isNotEmpty(deliverOidList)) {
            for (String deliverOid : deliverOidList) {
                String isKnow=rtOutRuleMapper.selectIsKnow(jobOid, deliverOid);
                if (isKnow== null){
                    isKnow="";
                }
                if (isKnow.equals("KNOWPUSH")||isKnow.equals("KNOWPUSHTEMP")){
                    throw RTErrorCodeEnum.KNOW_NOT_DELETE.getException("知识推送不允许删除");
                }
                rtOutRuleMapper.deleteDeliverLink(deliverOid);
                rtOutRuleMapper.deleteJobDeliverLink(jobOid, deliverOid);
            }

        }
    }

    @Around("execution(* com.hustcad.plm.rpm.service.remote.TyppmRemotePdmService.insertRemoteDoc(..))")
    public Object insertRemoteDoc(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        BatchInsertDocVO insertDocVO = (BatchInsertDocVO) args[0];
        List<DocDetailsVO> docList = insertDocVO.getDocList();
        Boolean isKnow=false;
        if (insertDocVO != null&&insertDocVO.getType().equals("KNOW")) {
            //insertDocVO.setType("IN");
            isKnow = true;

            Object proceed = point.proceed();
            for (DocDetailsVO docDetailsVO : docList) {
                RTTemplateLinkDocDTO rtTemplateLinkDocDTO = new RTTemplateLinkDocDTO();
                BigInteger oid = snowflakeIdComponent.getInstance().nextId();
                rtTemplateLinkDocDTO.setOid(oid);
                rtTemplateLinkDocDTO.setProjectId(new BigInteger(insertDocVO.getParentNodeOid()));
                //rtTemplateLinkDocDTO.setActivityID();
                rtTemplateLinkDocDTO.setOtype(docDetailsVO.getOtype());
                rtTemplateLinkDocDTO.setObjectNumber(docDetailsVO.getObjectNumber());
                rtTemplateLinkDocDTO.setIdentifierDisplayName(docDetailsVO.getName());
                rtTemplateLinkDocDTO.setDisplayVersion(docDetailsVO.getVersion());
                rtTemplateLinkDocDTO.setLatestVersionID(new BigInteger(docDetailsVO.getOid()));
                rtTemplateLinkDocDTO.setDocOType(docDetailsVO.getOtype());
                List<RTTemplateLinkDocDTO> rtTemplateLinkDocDTOList = new ArrayList<>();
                rtTemplateLinkDocDTOList.add(rtTemplateLinkDocDTO);
                rtProjectKnowledgeLinkMapper.batchInsertTempLinkDoc(rtTemplateLinkDocDTOList);
            }
            if (isKnow) {
                rtOutRuleMapper.updateJobKnow("IN", "KNOWPUSH");
                insertDocVO.setType("KNOW");
            }
        }
        return point.proceed();
    }

    //删除交付任务与交付物关联
    @Before("execution(* com.hustcad.plm.rpm.service.outrule.TyppmOutRuleService.deleteOutRuleDeliver(..))")
    public void deleteJobAndDeliver(JoinPoint point) throws Throwable {
        String ruleOid = (String) point.getArgs()[0];
        String linkOid = (String) point.getArgs()[1];
        if (!Objects.equals(ruleOid, "")&&ruleOid!=null &&!Objects.equals(linkOid, "")&&linkOid!=null){
            rtOutRuleMapper.deleteOutRuleDeliver(ruleOid, linkOid);
        }

    }
    //删除交付规则与交付物关联
    @Before("execution(* com.hustcad.plm.rpm.service.job.TyppmJobDeliverLinkService.deleteJobDeliverLinkByOidList(..))")
    public void deleteOutRuleAndDeliverLink(JoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        List<String> deliverOidList = (List<String>) args[0];
        List<BigInteger> deliverOidBigIntegerList = new ArrayList<>();
        if(CollUtil.isNotEmpty(deliverOidList)){
            for (String deliverOid : deliverOidList)
                deliverOidBigIntegerList.add(new BigInteger(deliverOid));
        }
        rtOutRuleMapper.deleteOutRuleDeliverLink(deliverOidBigIntegerList);
    }


    @Around("execution(* com.hustcad.plm.rpm.controller.job.JobController.updateJob(..))")
    public Object changeJobIbaStatus(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        TyppmJobDTO typpmJobDTO = (TyppmJobDTO) args[0];
        List<Map<String, Object>> tyProjectForm = typpmJobDTO.getTyProjectForm();
        if(CollUtil.isNotEmpty(tyProjectForm)) {
            Map<String, List<String>> ibaAttribute = new HashMap<>();
            for (Map<String, Object> map : tyProjectForm) {
                if (map.get("isIbaProperty") != null && (Boolean) map.get("isIbaProperty")) {
                    List<String> list = new ArrayList<>();
                    String ibaEnName = (String) map.get("ibaEnName");
                    String value = (String) map.get("value");
                    list.add(value);
                    ibaAttribute.put(ibaEnName, list);
                }
            }
            typpmJobDTO.setIbaAttribute(ibaAttribute);
        }
        return point.proceed();
    }

    /**
     * 任务关联问题报告时，将报告添加至参考文档
     * @param point
     * @return
     * @throws Throwable
     */
    @After("execution(* com.hustcad.plm.rpm.service.issue.TyppmProjectChangeIssueLinkService.batchCreatChangeIssueLinkByJob(..))")
    public void addChangeIssueToRemoteDoc(JoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        CreatIssueLinkDTO creatIssueLinkDTO = (CreatIssueLinkDTO) args[0];
        addRemoteDoc(creatIssueLinkDTO);
    }

    private void addRemoteDoc(CreatIssueLinkDTO creatIssueLinkDTO) {
        List<JSONObject> objectList = creatIssueLinkDTO.getObjectList();
        if(CollUtil.isEmpty(objectList)){
            return;
        }
        List<DocDetailsVO> docList = BeanUtil.copyToList(objectList, DocDetailsVO.class);
        BatchInsertDocVO batchInsetDocVO = new BatchInsertDocVO();
        batchInsetDocVO.setDocList(docList);
        batchInsetDocVO.setDocOtype("add");
        batchInsetDocVO.setLocalRepositoryUid("javaPDM");
        batchInsetDocVO.setParentNodeOid(creatIssueLinkDTO.getJobOid());
        batchInsetDocVO.setParentNodeOtype(TableTypeConstrant.TY_JOB_OTYPE);
        batchInsetDocVO.setProjectOid(creatIssueLinkDTO.getProjectOid());
        batchInsetDocVO.setType("IN");
        this.typpmRemotePdmService.insertRemoteDoc(batchInsetDocVO);
    }

    @After("execution(* com.hustcad.plm.rpm.service.issue.TyppmProjectChangeIssueLinkService.batchCreatChangeIssueLink(..))")
    public void addJobToRemoteDoc(JoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        CreatIssueLinkDTO creatIssueLinkDTO = (CreatIssueLinkDTO) args[0];

        String jobOtype = creatIssueLinkDTO.getJobOtype();
        if(StringUtils.isNotBlank(jobOtype) && StringUtils.isNotEmpty(jobOtype) && jobOtype.equals(TableTypeConstrant.TY_JOB_OTYPE)){
            addRemoteDoc(creatIssueLinkDTO);
            updateJobRiskType(creatIssueLinkDTO);
        }
    }

    private void updateJobRiskType(CreatIssueLinkDTO changeIssueDTO) throws IOException {
        List<JSONObject> objectList = changeIssueDTO.getObjectList();
        List<String> levelList = Arrays.asList("极高（81~99%）","很高（61~80%）","高（50~60%）","一般","低","很低");
        if (CollUtil.isEmpty(objectList)) {
            return;
        }
        String risk = "";
        JSONObject issue = objectList.get(0);
        JSONObject formJson = issue.getJSONObject("formData");
        if (formJson.containsKey("ProbabilityOccurrence")) {
            risk = formJson.getString("ProbabilityOccurrence");
        }
        if(StringUtils.isBlank( risk)){
            return;
        }
        String jobOid = changeIssueDTO.getJobOid();
        String currentRisk = taskMapper.selectJobRiskByOid(jobOid);
        int l1 = levelList.indexOf(risk);
        int l2 = levelList.indexOf(currentRisk);
        if(StringUtils.isEmpty(currentRisk)){
            taskMapper.updateJobRiskTypeByOid(jobOid, risk);
        }else {
            if(!levelList.contains(currentRisk)){
                taskMapper.updateJobRiskTypeByOid(jobOid, risk);
            }
            if(l1<l2){
                taskMapper.updateJobRiskTypeByOid(jobOid, risk);
            }
        }
    }
}

